<template>
  <div id="chatApp">
    <ChatHeader/>
    <main>
      <div class="sidebar">
        <div class="module active">
          <div class="module-header">
            <div class="module-icon">
              <i class="fas fa-comments"></i>
            </div>
            <h3>聽雨</h3>
          </div>
          <p>豆蔻娉娉含蕊时，象牙肌骨袜羊脂。</p>
          <p>天人道是衣无缝，自可冰心著白丝。</p>
        </div>
        <!--        <div class="image">-->
        <!--          <img src="../ai/Idea_Background_Image.jpg" alt="這是很棒的圖片">-->
        <!--        </div>-->
      </div>

      <div class="content">
        <MessageList
          :messages="messages"
          :is-typing="isTyping"
          ref="messageList"
        />
        <div class="input-area">
          <input type="text" placeholder="输入您的问题或指令..." v-model="userInput" @keyup.enter="sendMessage">
          <button @click="sendMessage"><i class="fas fa-paper-plane"></i> 发送</button>
          <button @click="clearMessages"><i class="fas fa-paper-plane"></i> 清除</button>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import ChatHeader from '@/components/ai/ChatHeader.vue'
import MessageList from '@/components/ai/MessageList.vue'

export default {
  name: 'AIChat',
  components: {
    ChatHeader,
    MessageList
  },
  data() {
    return {
      userInput: '',
      isTyping: false,
      messages: [
        {
          type: 'ai',
          content: '您好！我是AI智能助手，有什么可以帮您的吗？',
          isCode: false,
          time: '刚刚',
        },
      ],
    }
  },
  methods: {
    // 模拟API调用
    async aiChat(userInput) {
      try {
        const response = await fetch(`http://localhost:9912/ai/chat?prompt=${encodeURIComponent(userInput)}`);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.body;
      } catch (error) {
        console.error('API请求失败:', error);
        throw error;
      }
    },

    async sendMessage() {
      if (!this.userInput.trim()) return;

      // 添加用户消息
      this.messages.push({
        type: 'user',
        content: this.userInput,
        isCode: false,
        time: this.getCurrentTime()
      });

      const userInput = this.userInput;
      this.userInput = '';

      // 显示AI正在输入
      this.isTyping = true;
      try {
        // 调用AI聊天接口
        const stream = await this.aiChat(userInput);
        const reader = stream.getReader();
        const decoder = new TextDecoder('utf-8');

        // 添加初始AI消息
        this.messages.push({
          type: 'ai',
          content: '',
          isCode: false,
          time: '正在输入...'
        });

        const aiMessageIndex = this.messages.length - 1;
        let isCodeBlock = false;
        let fullContent = '';
        // 读取流数据
        while (true) {
          const {done, value} = await reader.read();
          if (done) {
            this.messages[aiMessageIndex].time = this.getCurrentTime();
            break;
          }

          // 解码并追加内容
          const text = decoder.decode(value, {stream: true});
          fullContent += text;
          this.messages[aiMessageIndex].content = fullContent;

          // 检测是否是代码
          if (!isCodeBlock && (
            text.includes('```') ||
            fullContent.includes('def ') ||
            fullContent.includes('function ') ||
            fullContent.includes('import ') ||
            fullContent.includes('class ') ||
            fullContent.includes('const ') ||
            fullContent.includes('let ') ||
            fullContent.includes('var ')
          )) {
            isCodeBlock = true;
          }

          this.messages[aiMessageIndex].isCode = isCodeBlock;

          // 滚动到底部
          this.scrollToBottom();
        }
      } catch (error) {
        console.error('Error:', error);
        this.messages.push({
          type: 'ai',
          content: '抱歉，发生了错误：' + error.message,
          isCode: false,
          time: this.getCurrentTime()
        });
      } finally {
        this.isTyping = false;
      }
    },
    clearMessages() {
      if (confirm('确定要清除所有聊天记录吗？')) {
        this.messages = [{
          type: 'ai',
          content: '您好！我是AI智能助手，有什么可以帮您的吗？',
          isCode: false,
          time: '刚刚'
        }];
      }
    },

    getCurrentTime() {
      const now = new Date();
      return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    },
    scrollToBottom() {
      this.$nextTick(() => {
        this.$refs.messageList.scrollToBottom();
      });
    }
  },
  watch: {
    messages: {
      handler() {
        this.scrollToBottom();
      },
      deep: true
    }
  },
  mounted() {
    this.scrollToBottom();
  }

}
</script>

<style scoped>
#chatApp {
  width: 100%;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 89vh;
}
main {
  display: flex;
  flex: 1;
  overflow: hidden;
}
.sidebar {
  width: 302px;
  background: #f8f9fa;
  padding: 25px 15px;
  border-right: 1px solid #e9ecef;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
}
.module {
  background: white;
  border-radius: 15px;
  padding: 18px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}
.module:hover {
  transform: translateY(-5px);
  border-color: #3494E6;
}
.module.active {
  border-color: #3494E6;
  background: #e3f2fd;
}
.module-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}
.module-icon {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  background: linear-gradient(45deg, #3494E6, #EC6EAD);
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
}
.module h3 {
  font-size: 1.1rem;
  color: #2c3e50;
}
.module p {
  font-size: 0.9rem;
  color: #7f8c8d;
  line-height: 1;
}
.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.input-area {
  padding: 20px;
  border-top: 1px solid #e9ecef;
  display: flex;
  gap: 15px;
  background: white;
}
input {
  flex: 1;
  padding: 15px 20px;
  border: 2px solid #e9ecef;
  border-radius: 50px;
  font-size: 1rem;
  outline: none;
  transition: all 0.3s ease;
}
input:focus {
  border-color: #3494E6;
}
button {
  background: linear-gradient(90deg, #3494E6, #EC6EAD);
  color: white;
  border: none;
  border-radius: 50px;
  padding: 0 25px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}
button:hover {
  transform: scale(1.05);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}
.image {
  width: 100%;
  height: 400px;
  position: relative;
}
.image img {
  width: 100%;
  height: 30%;
  object-fit: cover;
  display: block;
}

@media (max-width: 768px) {
  main {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid #e9ecef;
    padding: 15px;
  }
}
</style>
